<?php
/***
 * 
 * @author GuoLong
 * 2014/12/02
 * 
 */

class itemcollection extends Model {
/*
	id
	user_id
	item_id
	desc
	create_time
*/
	private $table="xdf_item_collection";
	private $fields=array("id");
	//根据id获取收藏题目，查看用户是否已经收藏一道题
	public function getCollectionItem($user_id,$item_id){
		$sql="SELECT `id` 
			FROM `$this->table`
			WHERE `user_id`=$user_id AND `item_id`='$item_id'"; 
 		//echo $sql;
		return $this->fetchRow($sql);
	}
	//获取收藏题目列表
	public function getCollectionItemList($user_id,$timestamp,$pagesize,$action,$subject_id,$start_datetime,$end_datetime){

		$filter=array();
		if($action=='pre'){
			$filter["preOrMore_sql"]=" TRUE";
		}
		if($action=='more'){
			$filter["preOrMore_sql"]=" ic.`id` < $timestamp ";
		}
		//SET subject filter
		if($subject_id<>"0"){ 
			$filter["subject"]=" i.`sub_id`='$subject_id' ";
		}else{
			$filter["subject"]="TRUE";
		}
		//SET time filter
		if($start_datetime<>"0" && $end_datetime<>"0"){
			$filter["time"]=" ic.`create_time`>='$start_datetime' AND ic.`create_time`<='$end_datetime' ";
		}else{
			$filter["time"]="TRUE";
		}
		
		$sql="SELECT ic.`item_id`,i.`content` as content,ic.`create_time`
		FROM `$this->table` ic
		LEFT JOIN `xdf_item` i ON i.`id`=ic.`item_id`  
		WHERE ic.`user_id`='$user_id' AND "
		.join(" AND ",$filter)
		." ORDER BY ic.`id` DESC LIMIT $pagesize";
		//echo $sql;
		$rows=$this->fetchAll($sql);
		if($rows)
		foreach ($rows as $key=> $val){
			$item_content_tmp=strip_tags($val["content"]);
			$order   = array("\r\n", "\n", "\r", "\t");
			$replace = ' ';
			// Processes \r\n's first so they aren't converted twice. 
			$item_content = str_replace($order, $replace, $item_content_tmp);	
			$rows[$key]["content"]=mb_substr($item_content, 0, 40, 'utf-8');
		}
// 		print_r($sql);
		return $rows;
	}
	//收藏题目
	public function collectItem($user_id,$item_id){
		$sql="INSERT INTO `xdf_item_collection`
			(`user_id`,`item_id`,`create_time`)
			values('$user_id','$item_id',now())";
// 	var_dump($sql);
		return $this->_db->insert($sql);		
	}
	//从收藏夹删除题目
	public function delItemFromCollection($user_id,$item_id){
		$sql="DELETE FROM `xdf_item_collection`
			WHERE `user_id`='$user_id' AND `item_id`='$item_id'";
		//echo $sql;
		return $this->_db->del($sql);
	}
}
